package com.example.administrator.social.activitys;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.social.R;
import com.example.administrator.social.model.Contact;
import com.example.administrator.social.util.AllenUtils;
import com.example.administrator.social.util.HttpUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener {
    private final static int NET_WORK_ERROR = 0;
    private final static int ADD_CONTACT = 1;
    private final static int UPDATE_UI = 3;
    TextView mRemarksText,mNickNameText,mAccountsTex,mPhoneText,
            mAgeText,mEmailText,mAddressText,mGoBackButton;
    ImageView mSexImage,mHeaderImage;
    Button mButtonAddContact,mButtonSendMessage,mButtonSendVideo;
    LinearLayout mSendMessageLayout;
    String mContactName;
    Context mContext;
    Contact mContact;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        mContext = this;
        AllenUtils.setActionBarColor(getWindow(), this, R.color.toolbar_color);
        mContact = (Contact) getIntent().getSerializableExtra("contact");
        mContactName = mContact.getName();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //发送请求更新数据
        requestGetInfo();
    }


    private void initView() {
        mRemarksText = (TextView) findViewById(R.id.contact_info_remarks);
        mSexImage = (ImageView) findViewById(R.id.contact_info_sex_image);
        mNickNameText = (TextView) findViewById(R.id.contact_info_account_numbers);
        mAccountsTex = (TextView) findViewById(R.id.text_accounts);
        mPhoneText = (TextView) findViewById(R.id.contact_info_phone_number);
        mAgeText = (TextView) findViewById(R.id.contact_info_age);
        mEmailText = (TextView) findViewById(R.id.contact_info_email);
        mAddressText = (TextView) findViewById(R.id.contact_info_address);
        mHeaderImage = (ImageView) findViewById(R.id.contact_info_header_image);
        mGoBackButton = (TextView) findViewById(R.id.contact_info_go_back);
        mButtonAddContact = (Button) findViewById(R.id.contact_info_add_contact);
        mButtonSendMessage = (Button) findViewById(R.id.contact_info_send_message_button);
        mSendMessageLayout = (LinearLayout) findViewById(R.id.send_message_layout);

        mButtonSendVideo = (Button) findViewById(R.id.contact_info_send_video_button);
        mButtonSendVideo.setOnClickListener(this);
        mButtonAddContact.setOnClickListener(this);
        mButtonSendMessage.setOnClickListener(this);
        mGoBackButton.setOnClickListener(this);
    }

    private void initData() {
     if (mContact!=null){
            if (mContact.getRemarks()!=null&&!mContact.getRemarks().equals("")){
                mRemarksText.setText(mContact.getRemarks());
                mNickNameText.setVisibility(View.VISIBLE);
            }else{
                mRemarksText.setText(mContact.getNickName());
                mNickNameText.setVisibility(View.GONE);
            }
            mNickNameText.setText(getResources().getString(R.string.contact_info_nick_name)+mContact.getNickName());
            mAddressText.setText(mContact.getAddress());
            mAccountsTex.setText(getResources().getString(R.string.contact_info_account_numbers)+mContact.getName());
            mPhoneText.setText(mContact.getPhone());
            mAgeText.setText(mContact.getAge());
            mEmailText.setText(mContact.getEmail());
            mSendMessageLayout.setVisibility(mContact.isFriend() ? View.VISIBLE : View.GONE);
            mButtonAddContact.setVisibility(mContact.isFriend()?View.GONE:View.VISIBLE);
            if (mContact.getHeaderImage()==null||mContact.getHeaderImage().equals("")){
                Glide.with(mContext).load(HttpUtils.HTTP_URL+"img/defualt_header_icon.jpeg").into(mHeaderImage);
            }else{
                Glide.with(mContext).load(mContact.getHeaderImage()).into(mHeaderImage);
            }
            if (mContact.getSex()==null||mContact.getSex().equals("")){
                mSexImage.setVisibility(View.GONE);
            }else{
                mSexImage.setImageResource(mContact.getSex().equals("男")?R.drawable.man_icon:R.drawable.woman_icon);
                mSexImage.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        //判断是否频繁点击同一个按钮。
        if (AllenUtils.isFrequentClick(mContext,id,System.currentTimeMillis()))return;
        switch (id){
            case R.id.contact_info_send_message_button:
                Intent messageIntent = new Intent(mContext,CharActivity.class);
                messageIntent.putExtra("contact",mContact);
                startActivity(messageIntent);
                break;
            case R.id.contact_info_send_video_button:
                //视频通话
                /*Intent videoIntent = new Intent(mContext,CharActivity.class);
                videoIntent.putExtra("contact",mContactName);
                startActivity(videoIntent);*/
                break;
            case R.id.contact_info_add_contact:
                //发送请求添加好友
                mHandler.sendEmptyMessage(ADD_CONTACT);
                break;
            case R.id.contact_info_go_back:
                finish();
                break;
        }
    }


    /**
     * 发送请求获取数据
     */
    private void requestGetInfo() {
        String url = HttpUtils.HTTP_URL+"searchOneUserInfo";
        Map<String,String> map = new HashMap<>();
        map.put("user",AllenUtils.getUserName(mContext));
        map.put("contact",mContactName);
        HttpUtils.postTextImageFile(mContext, url, map, null, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendEmptyMessage(NET_WORK_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                mContact = new Gson().fromJson(result,new TypeToken<Contact>(){}.getType());
                mHandler.sendEmptyMessage(UPDATE_UI);
            }
        });
    }

    /**
     * 发送请求添加好友
     */
    private void requestAddContact() {
        String url = HttpUtils.HTTP_URL+"addFriendRequestRecord";
        String date = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").format(new Date(System.currentTimeMillis()));
        Map<String, String> map = new HashMap<>();
        map.put("name_one",AllenUtils.getUserName(mContext));
        map.put("name_two", mContact.getName());
        map.put("date",date);
        map.put("phone",mContact.getPhone());
        HttpUtils.postTextImageFile(mContext, url, map, null, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendEmptyMessage(NET_WORK_ERROR);
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AllenUtils.showToast(mContext, getResources().getString(R.string.message_send_success));
                    }
                });
            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case ADD_CONTACT:
                    //发送请求申请添加好友
                    requestAddContact();
                    //发送通透消息通知对方
                    HttpUtils.sendAddRequestCmdMessage(mContact);
                    break;
                case UPDATE_UI:
                    initData();
                    break;
                case NET_WORK_ERROR:
                    AllenUtils.showToast(mContext,getResources().getString(R.string.network_error));
                    break;
            }
        }
    };

}
